package com.dmz.workflow.service.impl;

import com.alibaba.fastjson.JSON;
import com.dmz.workflow.dao.ApprovalNodeMapper;
import com.dmz.workflow.dto.ApprovalNode;
import com.dmz.workflow.dto.BranchNode;
import com.dmz.workflow.dto.ConditionOperation;
import com.dmz.workflow.service.ApprovalNodeService;
import com.dmz.workflow.util.ObjectUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Slf4j
@Service
public class ApprovalNodeServiceImpl implements ApprovalNodeService {

    @Autowired
    private ApprovalNodeMapper approvalNodeMapper;

    @Override
    public Set<String> queryUsedConditions(String processDefinitionId) {
        String json = approvalNodeMapper.findWorkJson(processDefinitionId);
        List<ApprovalNode> approvalNodes = JSON.parseArray(json, ApprovalNode.class);
        Set<String> usedConditions = new HashSet<>();
        if (!ObjectUtils.validateCollectionIsEmpty(approvalNodes)) {
            for (ApprovalNode approvalNode : approvalNodes) {
                List<BranchNode> conditions = approvalNode.getConditions();
                for (BranchNode condition : conditions) {
                    List<ConditionOperation> criteria = condition.getCriteria();
                    for (ConditionOperation criterion : criteria) {
                        usedConditions.add(criterion.getFormKey());
                    }
                }
            }
        }
        return usedConditions;
    }

    @Override
    public String queryProcessJson(String processDefinitionId) {
        return approvalNodeMapper.findWorkJson(processDefinitionId);
    }

    @Override
    public int queryMemberApprovingTask(Map<String, Object> requestParameter) {
        return approvalNodeMapper.queryMemberApprovingTask(requestParameter);
    }
}
